package logic

import (
	"context"
	"github.com/pkg/errors"
	"log"
	"recharge_srv/models"
	"recharge_srv/pkg"

	"recharge_srv/internal/svc"
	"recharge_srv/recharge"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *recharge.LoginRequest) (*recharge.LoginResponse, error) {
	// todo: add your logic here and delete this line

	//用户登录
	var u models.User
	u.Mobile = in.Mobile
	err := u.ShowUser()
	if err != nil {
		logx.Error("登录失败:", err)
		return nil, err
	}

	if u.ID == 0 {
		log.Println("注册账号")
		u.Password = pkg.Md5(in.Password)
		err = u.Register()
		if err != nil {
			logx.Error("登录失败:注册失败", err)
			return nil, err
		}
	} else {
		log.Println("账号登录")
		if u.Password != pkg.Md5(in.Password) {
			logx.Error("登录失败:", errors.New("用户名或密码错误"))
			return nil, errors.New("用户名或密码错误")
		}
	}

	return &recharge.LoginResponse{UserId: int64(u.ID)}, nil
}
